<?php


namespace app\admin\controller\user;


use app\admin\model\SystemErrorLog;
use app\admin\model\UserBase;
use app\admin\service\TriggerService;
use app\common\constants\AdminConstant;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;

/**
 * Class User
 * @package app\admin\controller\user
 * @ControllerAnnotation(title="会员管理")
 */
class User extends AdminController
{

    use \app\admin\traits\Curd;

    protected $sort = [
//        'sort' => 'desc',
        'id' => 'desc',
//        'create_time'  => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = UserBase::init();
//        $this->assign('auth_list', $this->model->getAuthList());
    }

    /**
     * @NodeAnotation(title="会员列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParams();
            foreach ($where as $k => $condition) {
                if ($condition[0] == 'nickname') {
                    $where[$k][2] = "%" . base64_encode(trim($condition[2], '%')) . "%";
                }
            }
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
//                ->withoutField('password')
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            //处理信息
//            $list = $this->model->format_user($list);
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        $this->error('暂不允许后台添加');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $authIds = $this->request->post('auth_ids', []);
            $post['auth_ids'] = implode(',', array_keys($authIds));
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
//        dd($this->request->url(true));
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->except(['__token__', 'file']);
            $rule = [
                'mobile' => 'mobile',
            ];
            $message = [
                'mobile.mobile' => '填写有效的手机号',
            ];
            $this->validate($post, $rule, $message);
            try {
                $save = $row->save($post);
//                TriggerService::updateMenu($id);
            } catch (\Exception $e) {
                (new SystemErrorLog())->addError($e->getMessage());
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
//        $row->auth_ids = explode(',', $row->auth_ids);
        $this->assign('row', $row);
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
//        dd(config('app.user.delete'));
        //TODO 有订单用户禁止删除，目前全部禁止
        !config('app.user.delete') && $this->error('请勿删除会员');
//        $id == AdminConstant::SUPER_ADMIN_ID && $this->error('超级管理员不允许修改');
        if (is_array($id)) {
            if (in_array(AdminConstant::SUPER_ADMIN_ID, $id)) {
                $this->error('超级管理员不允许修改');
            }
        }
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID' => 'require',
            'field|字段' => 'require',
            'value|值' => 'require',
        ];
        $this->validate($post, $rule);
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
//        if ($post['id'] == AdminConstant::SUPER_ADMIN_ID && $post['field'] == 'status') {
//            $this->error('超级管理员状态不允许修改');
//        }
        $row = $this->model->find($post['id']);
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }


}
